package cn.dujc.superkid.fragment.main;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.dujc.core.adapter.BaseQuickAdapter;
import cn.dujc.core.ui.BaseListFragment;
import cn.dujc.superkid.R;
import cn.dujc.superkid.activities.ChannelActivity;
import cn.dujc.superkid.activities.CourseDetailActivity;
import cn.dujc.superkid.activities.MainActivity;
import cn.dujc.superkid.activities.OnlineAnswerActivity;
import cn.dujc.superkid.activities.ResearchActivity;
import cn.dujc.superkid.activities.SearchActivity;
import cn.dujc.superkid.adapter.CourseAdapter;
import cn.dujc.superkid.api.HttpHelper;
import cn.dujc.superkid.api.QMap;
import cn.dujc.superkid.api.Result;
import cn.dujc.superkid.api.ResultCallBack;
import cn.dujc.superkid.bean.ChannelEntity;
import cn.dujc.superkid.bean.CourseEntity;
import cn.dujc.superkid.bean.CourseResult;
import cn.dujc.superkid.bean.SlideEntity;
import cn.dujc.superkid.configs.Globals;
import cn.dujc.superkid.utils.Preferences;
import cn.dujc.superkid.widgets.banner.DuBanner;
import retrofit2.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseListFragment implements View.OnClickListener {

    private final String[] mTabTexts = {"精品课程", "最新课程"};
    private final List<CourseEntity> mList = new ArrayList<>();
    private CourseAdapter mAdapter;
    private TextView mMenu;
    private View mHeaderView;
    private DuBanner mDuBanner;
    private int mPage = 1;
    private int mType = 0;//0精品课程 1最新课程

    @Nullable
    @Override
    protected BaseQuickAdapter initAdapter() {
        return mAdapter = new CourseAdapter(mList);
    }

    @Nullable
    @Override
    public Toolbar initToolbar(ViewGroup parent) {
        final Toolbar toolbar = (Toolbar) LayoutInflater.from(parent.getContext()).inflate(R.layout.toolbar_main, parent, false);
        mMenu = toolbar.findViewById(R.id.toolbar_menu_id);
        toolbar.findViewById(R.id.toolbar_title_id).setOnClickListener(this);
        mMenu.setOnClickListener(this);
        return toolbar;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        super.initBasic(savedInstanceState);
        mAdapter.addHeaderView(setupHeaderView(null));
    }

    @Override
    protected void onItemClick(int position) {
        starter()
                .with(CourseDetailActivity.EXTRA_COURSE, mAdapter.getItem(position))
                .go(CourseDetailActivity.class);
    }

    @Override
    protected void loadMore() {
        loadData();
    }

    @Override
    protected void reload() {
        showRefreshing();
        loadBanner();
        mPage = 1;
        loadData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_menu_id: {
                starter().go(ChannelActivity.class);
            }
            break;
            case R.id.toolbar_title_id: {
                starter().go(SearchActivity.class);
            }
            break;
            case R.id.ll_choise_lesson: {
                ((MainActivity) getActivity()).initFragment(1);
            }
            break;
            case R.id.ll_about_research: {
                starter().go(ResearchActivity.class);
            }
            break;
            case R.id.ll_user_center: {
                ((MainActivity) getActivity()).initFragment(4);
            }
            break;
            case R.id.ll_answer_online: {
                starter().go(OnlineAnswerActivity.class);
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMenu.setText(Preferences.getInstance().getChannel(mActivity).getChannel_name());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == starter().getRequestCode(ChannelActivity.class)) {
//                mMenu.setText(Preferences.getInstance().getChannel(mActivity).getChannel_name());
                reload();
                ((MainActivity)mActivity).refreshFragmentData();
            }
        }
    }

    private View setupHeaderView(List<SlideEntity> slides) {
        if (mHeaderView == null) {
            mHeaderView = getLayoutInflater().inflate(R.layout.header_home, null);
            mHeaderView.findViewById(R.id.ll_choise_lesson).setOnClickListener(this);
            mHeaderView.findViewById(R.id.ll_about_research).setOnClickListener(this);
            mHeaderView.findViewById(R.id.ll_user_center).setOnClickListener(this);
            mHeaderView.findViewById(R.id.ll_answer_online).setOnClickListener(this);
            mDuBanner = mHeaderView.findViewById(R.id.db_banner);
            TabLayout tabLayout = mHeaderView.findViewById(R.id.tl_tabs);
            for (String tab : mTabTexts) tabLayout.addTab(tabLayout.newTab().setText(tab));
            tabLayout.clearOnTabSelectedListeners();
            tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    mType = mTabTexts[0].equals(tab.getText()) ? 0 : 1;
                    reload();
                }
                @Override
                public void onTabUnselected(TabLayout.Tab tab) { }

                @Override
                public void onTabReselected(TabLayout.Tab tab) { }
            });
        }
        if (slides != null) {
            mDuBanner.setData(slides);
        }
        return mHeaderView;
    }

    private void loadBanner() {
        HttpHelper.getHome().slide(QMap.build().create()).enqueue(new ResultCallBack<Result<List<SlideEntity>>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<List<SlideEntity>> body) {
                if (body != null) {
                    setupHeaderView(body.getData());
                }
            }
        });
    }

    private void loadData() {
        final QMap.Builder map = QMap.build();
        final ChannelEntity channel = Preferences.getInstance().getChannel(mActivity);
        if (channel != null) map.put("channel", channel.getChannel_id());
//        map.put("num", 3);
//        map.put("page", mPage);
        final Call<Result<CourseResult>> course;
        if (mType == 0) {
            course = HttpHelper.getHome().excellentCourse(map.create());
        } else {
            course = HttpHelper.getHome().newCourse(map.create());
        }
        course.enqueue(new ResultCallBack<Result<CourseResult>>(mActivity) {
            @Override
            public void onSuccessCallback(int code, Result<CourseResult> body) {
                if (mPage <= 1) mList.clear();
                boolean done = false;
                if (body != null) {
                    final CourseResult data = body.getData();
                    if (data != null) {
                        final List<CourseEntity> list = data.getList();
                        if (list != null) {
                            mList.addAll(list);
                        }
                        done = mPage >= data.getPage_num();
                    }
                }
                notifyDataSetChanged(done);
                mPage++;
            }

            @Override
            public void onFailureCallback(int code, String msg) {
                super.onFailureCallback(code, msg);
                loadFailure();
            }
        });
    }

}